<?php
/**
 * ***********************************************************************************
 * 咨询鲤 PC端知识店铺首页
 * 
 * @author Mr.RJH
 * @date 2025-09-02
 * @email<15213026209@163.com>
 * ***********************************************************************************
 */
namespace app\controller;

use app\BaseController;

use think\facade\Cache;
use think\facade\Request;

use app\model\merchant\ZxlMerchantModel;
use app\model\merchant\ZxlKnowStorePcBannerModel;
use app\model\merchant\ZxlKnowStorePcPageModel;
use app\model\merchant\ZxlKnowStorePcSettingModel;
use app\model\merchant\ZxlKnowStoreWeixinMiniprogramAuthorizeModel;

use app\model\product\ZxlKnowStoreProductModel;
use app\model\product\ZxlKnowStoreProductAttrModel;
use app\model\product\ZxlKnowStoreCategoryModel;

use app\model\article\ZxlKnowStoreArticleModel;

use app\service\ProductService;

class Index extends BaseController
{
    public function index()
    {
        $productService = new ProductService($this->request->m_id);
        
        // 轮播
        $banner_list = $this->get_banner(1);

        // 轮播右侧广告位
        $banner_side = $this->get_banner(2);

        // 题库推荐广告
        $qu_advert = $this->get_banner(3, 1);

        // 课程推荐广告
        $course_advert = $this->get_banner(3, 2);

        // 实物推荐广告
        $goods_advert = $this->get_banner(3, 3);

        // 直播推荐
        $live_list = $productService->recommend_product(6, 6);

        // 题库推荐
        $qu_limit = 8;
        if ($qu_advert) {
            $qu_limit = 6;
        }
        $question_list = $productService->recommend_product(5, $qu_limit);

        // 课程推荐
        $course_limit = 8;
        if ($course_advert) {
            $course_limit = 6;
        }
        $course_list = $productService->recommend_product(3, $course_limit);
        
        // 实物推荐
        $goods_limit = 8;
        if ($goods_advert) {
            $goods_limit = 6;
        }
        $goods_list = $productService->recommend_product(1, $goods_limit);

        // 资讯推荐
        $article_list = ZxlKnowStoreArticleModel::where(['m_id' => $this->request->m_id, 'status' => 1, 'is_delete' => 0])->order('click_num', 'desc')->limit(6)->select()->toArray();
        foreach ($article_list as &$v) {
            $two_cate = ZxlKnowStoreCategoryModel::where(['id' => $v['cate_id']])->find();
            $first_name = ZxlKnowStoreCategoryModel::where(['id' => $two_cate['parent_id']])->value('name');
            $v['cat_names'] = $first_name.'<span lay-separator="" style="margin:5px;color:#c2c2c2;">/</span>'.$two_cate['name'];
        }

        $this->assign('banner_list', $banner_list);
        $this->assign('banner_side', $banner_side);
        $this->assign('qu_advert', $qu_advert);
        $this->assign('course_advert', $course_advert);
        $this->assign('goods_advert', $goods_advert);
        $this->assign('live_list', $live_list);
        $this->assign('question_list', $question_list);
        $this->assign('course_list', $course_list);
        $this->assign('goods_list', $goods_list);
        $this->assign('article_list', $article_list);
        return $this->fetch();
    }

    /**
     * 获取广告图
     * 
     * @param int $position 广告位置
     * @param int $recommend_slot 推荐位
     * @return array
     */
    private function get_banner($position, $recommend_slot='')
    {
        $where = function($q)use($position, $recommend_slot){
            $q->where('m_id', $this->request->m_id);
            $q->where('position', $position);
            $q->where('is_delete', 0);
            $q->where('status', 1);
            if ($recommend_slot != '') {
                $q->where('recommend_slot', $recommend_slot);
            }
        };
        $banner_list = ZxlKnowStorePcBannerModel::where($where)->order(['sort' => 'desc', 'create_time' => 'desc'])->select()->toArray();
        foreach ($banner_list as &$v) {
            $page = ZxlKnowStorePcPageModel::find($v['id']);
            if ($page) {
                $v['href'] = $page['path_url'];
                if ($page['is_param'] == 1) {
                    $v['href'] = $page['path_url'].'?id='.$v['page_param'];
                }
            }
            
        }
        return $banner_list;
    }

    /**
     * PC端商户申请独立域名审核通过生成Apache虚拟主机配置
     * 
     * @return json
     */
    public function approveDomain()
    {
        if ($this->request->isPost()) {

            $domainId = $this->request->param('domain_id');
            try {
                $domainRecord = ZxlKnowStorePcSelfDomainModel::find($domainId);
                if (!$domainRecord) {
                    throw new \Exception('域名申请记录不存在');
                }
                $apacheConfigService = new ApacheConfigService();
                $domainRecord['pem'] = @file_get_contents($domainRecord['pem_url']);
                $domainRecord['key'] = @file_get_contents($domainRecord['key_url']);
                // 生成Apache配置
                $config = $apacheConfigService->generateVhostConfig(
                    $domainRecord->domain,
                    $domainRecord->pem ?? '',
                    $domainRecord->key ?? ''
                );
                
                // 保存SSL证书
                $certSaved = $apacheConfigService->saveSSLCertificates(
                    $domainRecord->domain,
                    $domainRecord->pem ?? '',
                    $domainRecord->key ?? ''
                );
                if (!$certSaved) {
                    throw new \Exception('SSL证书保存失败');
                }
                
                // 部署配置
                $deployed = $apacheConfigService->deployConfig(
                    $domainRecord->domain,
                    $config
                );
                if (!$deployed) {
                    throw new \Exception('Apache配置部署失败');
                }
                
                // 更新数据库记录
                $domainRecord->save([
                    'status'        => 1,
                    'apache_config' => $config,
                    'audit_time'    => time(),
                ]);
                return json(['code' => 0,'msg' => '部署成功']);
            } catch (\Exception $e) {
                return json(['code' => 1,'msg' => $e->getMessage()]);
            }
            
        }
    }
}
